package org.icy.plugins;

import java.util.ArrayList;

import org.ice.logger.Logger;
import org.icy.core.message.Observer;
import org.icy.exceptions.IcySetupException;

public class PluginManager implements Observer {

	public ArrayList<Plugin> plugins = new ArrayList<Plugin>();
	
	/**
	 * Register a plugin
	 * @param plugin the plugin to be registered
	 */
	public void install(Plugin plugin) {
		if (!plugins.contains(plugin))	{
			plugins.add(plugin);
			try {
				plugin.load();
			} catch (IcySetupException ex) {
				Logger.getLogger().log("Error while registering plugin: ["+plugin.getName()+"]: "+ex.toString(), Logger.LEVEL_WARNING);
				plugins.remove(plugin);
			}
		}
	}
	
	/**
	 * Activate a plugin
	 * @param plugin the plugin to be activated
	 */
	public void activate(Plugin plugin) {
		if (plugins.contains(plugin)) {
			try {
				plugin.activate();
			} catch (IcySetupException ex) {
				Logger.getLogger().log("Error while activating plugin ["+plugin.getName()+"]: "+ex.toString(), Logger.LEVEL_WARNING);
			}
		}
	}
	
	/**
	 * Deactivate a plugin
	 * @param plugin the plugin to be deactivated
	 */
	public void deactivate(Plugin plugin) {
		if (plugins.contains(plugin)) {
			try {
				plugin.deactivate();
			} catch (IcySetupException ex) {
				Logger.getLogger().log("Error while deactivating plugin ["+plugin.getName()+"]: "+ex.toString(), Logger.LEVEL_WARNING);
			}
		}
	}
	
	/**
	 * Deregister a plugin
	 * @param plugin the plugin to be deregistered
	 */
	public void deregister(Plugin plugin) {
		if (plugins.contains(plugin))	{
			try {
				plugin.unload();
			} catch (IcySetupException ex) {
				Logger.getLogger().log("Error while deregistering plugin ["+plugin.getName()+"]: "+ex.toString(), Logger.LEVEL_WARNING);
			}
			plugins.remove(plugin);
		}
	}

	@Override
	public void onMessage(String message, Object data) {
		for(Plugin plugin: plugins) {
			try {
				plugin.onMessage(message, data);
			} catch (Exception ex) {
				Logger.getLogger().log("Plugin ["+plugin.getName()+"] error on event ["+message+"]: "+ex.toString(), Logger.LEVEL_WARNING);
			}
		}
	}
	
}
